/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FormItensVenda.java
 *
 * Created on 07/09/2011, 12:27:38
 */
package javalee.forms;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javalee.util.Uteis;
import javalee.dao.ItemVendaDAO;
import javalee.dao.ProdutoDAO;
import javalee.maps.ItensVenda;
import javalee.maps.Produto;
import javalee.maps.Venda;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author will
 */
public class FormItensVenda extends javax.swing.JFrame {
    private ProdutoDAO prodDAO;
    private ItemVendaDAO itemDAO;
    private Venda pai;
    /** Creates new form FormItensVenda */
    public FormItensVenda() {
        initComponents();
        prodDAO = new ProdutoDAO();
        itemDAO = new ItemVendaDAO();
        pai = new Venda();
    }
    
    public void setIdVenda(int idVenda){
        pai.setId(idVenda);
    }
    
    private void listaProdutos(){
        if(!Uteis.validaCampoTexto(txtBusca)){
            JOptionPane.showMessageDialog(null,"Campo de pesquisa está incorreto.");
        }
        else{
     //Trago a lista de maquinas do banco
     ArrayList<Produto> lista = prodDAO.consultarSemIdVenda(pai.getId(),txtBusca.getText().toString());
     tbProdutos.removeAll();
     
     //Pego o TableModel do componente JTable
     DefaultTableModel tableModel = (DefaultTableModel)tbProdutos.getModel();  
     //Limpo os dados do componente
     tableModel.setNumRows(0);
     
     //Passo pela lista de Maquinas, inserindo no JTable
     for(Iterator<Produto> it = lista.iterator(); it.hasNext();){
        Produto p = (Produto)it.next();
        tableModel.addRow(new Object[]{
            p.getId(),
            p.getDescricao()
        });     
    }   
        }
}
 
    private void limpaDados(){
        txtBusca.setText("");
        txtQtd.setText("");
    }
    
    private void listaItensVenda(){
        
    try{
        ArrayList<ItensVenda> lista = itemDAO.consultar(pai);
    
     tbComponentes.removeAll();
     
     
     DefaultTableModel tableModel = (DefaultTableModel)tbComponentes.getModel();  
     
     tableModel.setNumRows(0);
     
     
     for(Iterator<ItensVenda> it = lista.iterator(); it.hasNext();){
        ItensVenda i = (ItensVenda)it.next();
        tableModel.addRow(new Object[]{
            i.getProduto().getId(),
            i.getProduto().getDescricao(),
            i.getQtdade()
        });     
    }
    }
    catch(Exception e){
        System.out.println(e.toString());
    }   
    }
    
    private void insereItens(){
        if(tbProdutos.getSelectedRow()==-1){
            JOptionPane.showMessageDialog(null, "Selecione um item.");
        }
        else if("".equals(txtQtd.getText())){
            JOptionPane.showMessageDialog(null, "Insira uma quantidade do item.");
        }
        else{
        int row = tbProdutos.getSelectedRow();
    try{
        DefaultTableModel tableModel = (DefaultTableModel)tbProdutos.getModel();  
        ItensVenda item = new ItensVenda();
        item.setVenda(pai);
        item.setProduto(new Produto(Integer.parseInt(tableModel.getValueAt(row, 0).toString())));
        item.setQtdade(Integer.parseInt(txtQtd.getText()));

        itemDAO.cadastrar(item);

        limpaDados();
        listaProdutos();
        listaItensVenda();
    }
    catch(Exception e){
        System.out.println(e.toString());
    }
        }
    } 

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbComponentes = new javax.swing.JTable();
        txtBusca = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbProdutos = new javax.swing.JTable();
        btnOk = new javax.swing.JButton();
        lbQtd = new javax.swing.JLabel();
        btnSair = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        txtQtd = new javax.swing.JFormattedTextField(java.text.NumberFormat.getInstance());

        setTitle("Formulario de Itens na Venda");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        tbComponentes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Produto", "Quantidade"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbComponentes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbComponentesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbComponentes);

        txtBusca.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscaKeyReleased(evt);
            }
        });

        tbProdutos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Produto"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(tbProdutos);

        btnOk.setText("Ok");
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        lbQtd.setText("Qtdade : ");

        btnSair.setText("Sair");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        btnExcluir.setText("Excluir");
        btnExcluir.setEnabled(false);
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtBusca, javax.swing.GroupLayout.DEFAULT_SIZE, 452, Short.MAX_VALUE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(195, 195, 195)
                        .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(126, 126, 126)
                        .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(191, 191, 191)
                        .addComponent(lbQtd)
                        .addGap(2, 2, 2)
                        .addComponent(txtQtd, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtBusca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(5, 5, 5)
                        .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 341, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(btnOk)
                                .addComponent(txtQtd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(lbQtd))
                            .addComponent(btnExcluir))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(34, 34, 34))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void txtBuscaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscaKeyReleased
    if(evt.getKeyCode() == 10){
    listaProdutos();
    }
    // TODO add your handling code here:
}//GEN-LAST:event_txtBuscaKeyReleased

private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed
    insereItens();
}//GEN-LAST:event_btnOkActionPerformed

private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
    dispose();
}//GEN-LAST:event_btnSairActionPerformed

private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
    if(tbComponentes.getSelectedRow()==-1){
        JOptionPane.showMessageDialog(null, "Selecione um item.");
        btnExcluir.setEnabled(false);
    }
    else{
    int row = tbComponentes.getSelectedRow();
    try{
    DefaultTableModel tableModel = (DefaultTableModel)tbComponentes.getModel();  
    ItensVenda item = new ItensVenda();
    item.setVenda(pai);
    item.setProduto(new Produto(Integer.parseInt(tableModel.getValueAt(row, 0).toString())));
     
    itemDAO.excluir(item);
    
    limpaDados();
    listaProdutos();
    listaItensVenda();
    }
    catch(Exception e){
        System.out.println(e.toString());
    }
    // TODO add your handling code here:
    }
}//GEN-LAST:event_btnExcluirActionPerformed

private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
    listaProdutos();
    listaItensVenda();
}//GEN-LAST:event_formWindowActivated

private void tbComponentesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbComponentesMouseClicked
btnExcluir.setEnabled(true);
    // TODO add your handling code here:
}//GEN-LAST:event_tbComponentesMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnOk;
    private javax.swing.JButton btnSair;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lbQtd;
    private javax.swing.JTable tbComponentes;
    private javax.swing.JTable tbProdutos;
    private javax.swing.JTextField txtBusca;
    private javax.swing.JFormattedTextField txtQtd;
    // End of variables declaration//GEN-END:variables
}
